package com.yc.javaee.网络编程;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;

/**
 * 获取服务器资源
 */
public class URL类 {

    public static void main(String[] args) throws IOException {

        URL url = new URL("http://www.hyycinfo.com:80/index.html?a=100&b=200");
        System.out.println("============== 地址信息 ===============");
        System.out.println("协议:" + url.getProtocol());
        System.out.println("主机地址:" + url.getHost());
        System.out.println("端口:" + url.getPort());
        System.out.println("地址:" + url.getPath());
        System.out.println("参数:" + url.getQuery());
        System.out.println("文件:" + url.getFile());

        URLConnection conn = url.openConnection();
        System.out.println("============== 资源信息 ===============");
        System.out.println("内容类型:" + conn.getContentType());
        System.out.println("最后修改时间:" + new Date(conn.getLastModified()));
        System.out.println("文件大小:" + conn.getContentLength());
        System.out.println("文件大小long类型:" + conn.getContentLengthLong());
        System.out.println("字符集编码:" + conn.getContentEncoding());

        try (InputStreamReader isr = new InputStreamReader(conn.getInputStream());
             BufferedReader br = new BufferedReader(isr)) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        }

        URL url1 = new URL("http://www.hyycinfo.com/images/30.jpg");
        InputStream inputStream = url1.openConnection().getInputStream();

        try (FileOutputStream fos = new FileOutputStream("d:/30.jpg")) {
            byte[] buffer = new byte[1024];
            int count;
            while ((count = inputStream.read(buffer)) > -1) {
                fos.write(buffer, 0, count);
            }
        }

    }


}
